﻿namespace Toolkit.Lib.CodeModels;

/// <summary>
/// 源文件类
/// </summary>
public class SourceFileModel
{
    #region Prop

    /// <summary>
    /// 文件路径
    /// </summary>
    public string FilePath { get; set; }

    /// <summary>
    /// 文件大小(字节)，可能为null
    /// </summary>
    public readonly long? FileSize;

    /// <summary>
    /// 文件名
    /// </summary>
    public string FileName { get; set; }

    /// <summary>
    /// 编程语言
    /// </summary>
    public string Language
    {
        get
        {
            if (string.IsNullOrWhiteSpace(FileName))
                return string.Empty;
            var ext = Path.GetExtension(FileName)[1..];
            return ext switch
            {
                "cs" => "C#",
                "cpp" => "C++",
                "java" => "Java",
                "h" => "C/C++",
                "js" => "JavaScript",
                "ts" => "TypeScript",
                "py" => "Python",
                "vue" => "Vue",
                _ => ext.ToUpper()
            };
        }
    }

    /// <summary>
    /// 是否为源代码文件
    /// </summary>
    public bool IsCodeFile
    {
        get
        {
            if (string.IsNullOrWhiteSpace(FileName))
                return false;
            var ext = Path.GetExtension(FileName).Length > 2
                ? Path.GetExtension(FileName)[1..]
                : Path.GetExtension(FileName);
            return Extensions.Any(x => x == ext);
        }
    }

    #endregion

    public SourceFileModel(string filePath)
    {
        FilePath = filePath;
        FileName = Path.GetFileName(filePath);
        if (!File.Exists(filePath)) return;
        FileSize = new FileInfo(filePath).Length;
    }

    public string[] Extensions
        => new[]
        {
            "bat", "sh", "c", "cpp", "hpp", "h", "hxx", "go", "rs", "rust", "mm", "swift", "cs", "fs", "vb", "vba",
            "java", "jsp", "kt", "dart", "groovy", "lua", "js", "ts", "scss", "css", "vue", "html", "py", "py2", "py3",
            "jl", "m", "R", "php", "sql", "xml", "yaml", "json", "xaml", "axaml", "svg",
        };
}

public class GitIgnore
{
    private readonly string[] _ignoreList;

    public GitIgnore(string[] ignoreList)
    {
        _ignoreList = ignoreList;
    }

    public bool IsIgnored(string path)
    {
        foreach (var ignore in _ignoreList)
        {
            if (ignore.StartsWith("#")) //忽略注释
                continue;
            if (ignore.EndsWith("/") && path.StartsWith(ignore.Substring(0, ignore.Length - 1))) //忽略文件夹
                return true;
            if (path.EndsWith(ignore)) //忽略文件
                return true;
        }

        return false;
    }
}